<template>
  <div class="cart">
    <div class="nav">
      <div class="safeguard">
        <span>
          <van-icon name="passed" />
          100%正品保证
        </span>
        <span>
          <van-icon name="passed" />
          所有商品精挑细选
        </span>
        <span>
          <van-icon name="passed" />
          售后无忧
        </span>
      </div>
      <div class="purchaseNum">
        <span>购物数量</span>
        <span class="num">{{
          data_cartproduct ? data_cartproduct.length : 0
        }}</span>
        <template v-if="data_cartproduct ? data_cartproduct.length != 0 : false">
          <button
            class="btn"
            v-if="data_cartproduct != [] && !administration"
            @click="administration = true"
          >
            管理
          </button>
          <button class="btn" v-else @click="administration = false">
            取消
          </button>
        </template>
      </div>
    </div>
    <div class="productList">
      <div class="empty" v-if="data_cartproduct == '' || !data_cartproduct">
        <van-empty
          class="custom-image"
          image="http://47.115.51.185/h5/img/noCart.6f2abfef.png"
        />
      </div>
      <transition-group tag="ul" v-else class="goodslist" name="slide">
        <CartCard
          v-for="item in data_cartproduct"
          :key="item.id"
          :item="item"
          :AllSelectedflag="checked"
          :All="All"
          @computedSelected="computedSelected"
          @computedPrice="computedPrice"
          @AllFlag="All = $event"
          @accessCollect="accessCollect"
          :closeSelected="closeSelected"
        ></CartCard>
      </transition-group>
    </div>
    <template v-if="data_cartproduct == '' || !data_cartproduct">
      <RecommendForYou></RecommendForYou>
    </template>
    <div class="statistics" v-else>
      <div class="selected">
        <van-checkbox
          v-model="checked"
          checked-color="#ee0a24"
          @click="selectedAll"
          >全选({{ selectedNum }})</van-checkbox
        >
      </div>
      <div class="purchase">
        <template v-if="!administration">
          <span>￥{{ totalprice.toFixed(2) }}</span>
          <button class="purchase_order" @click="playOrder">立即下单</button>
        </template>
        <template v-else>
          <button class="collect" @click="addCollect">收藏</button>
          <button class="del" @click="del">删除</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations } from "vuex";
import CartCard from "@/components/CartCard";
import RecommendForYou from "@/components/RecommendForYou";
export default {
  components: {
    CartCard,
    RecommendForYou,
  },
  data() {
    return {
      checked: false,
      totalprice: 0,
      totalNum: 0,
      selectedNum: 0,
      All: false,
      administration: false,
      collectlist: [],
      closeSelected:false
    };
  },
  created() {
    this.getlist();
  },
  methods: {
    ...mapActions(["getList"]),
    ...mapMutations(["getCartProduct"]),
    getlist() {
      this.axios.get("/api/cart/list").then((response) => {
        this.getCartProduct(response.data.data.valid);
      });
    },
    computedPrice(price, flag) {
      if (flag) {
        this.totalprice += Number(price);
      }
    },
    computedSelected(flag) {
      if (flag) {
        this.selectedNum++;
      } else {
        this.selectedNum--;
      }
    },
    selectedAll() {
      this.All = false;
      if(this.selectedNum == this.data_cartproduct.length && !this.checked){
        this.closeSelected = !this.closeSelected
      }
      if (this.checked) {
        this.data_cartproduct.forEach((item) => {
          this.collectlist.push({
            ...item,
            storeInfo: {
              id: item.product_id,
            },
          });
        });
      } else {
        this.collectlist= []
      }
    },
    accessCollect(flag, params) {
      if (flag) {
        this.collectlist.push({
          ...params,
          storeInfo: {
            id: params,
          },
        });
      } else {
        this.collectlist = this.collectlist.filter((item) => {
          return params != item.storeInfo.id;
        });
      }
    },
    addCollect() {
      var Ids = [];
      this.collectlist.filter((item) => {
        Ids.push(item.product_id);
      });
      this.axios
        .post("/api/collect/all", {
          category: "product",
          id: Ids,
        })
        .then((response) => {
          this.$toast(response.data.msg);
        });
    },
    del() {
      this.selectedNum = this.selectedNum - this.collectlist.length;
      var math = this.collectlist.map((item) => {
        return item.cart_num * item.productInfo.price;
      });
      var num = 0;
      for (var i = 0; i < math.length; i++) {
        num += math[i];
      }
      this.totalprice = this.totalprice - num;
      var Ids = [];
      this.collectlist.filter((item) => {
        Ids.push(item.id);
      });
      this.axios
        .post("/api/cart/del", {
          ids: Ids,
        })
        .then((response) => {
          console.log(response.data.msg);
          this.getlist();
          this.collectlist = [];
          localStorage.setItem("cartSelectedList", []);
        });
    },
    playOrder() {
      if (this.collectlist.length == 0) {
        this.$toast("请选择产品");
      } else {
        this.selectedNum = this.selectedNum - this.collectlist.length;
        var math = this.collectlist.map((item) => {
          return item.cart_num * item.productInfo.price;
        });
        var num = 0;
        for (var i = 0; i < math.length; i++) {
          num += math[i];
        }
        this.totalprice = this.totalprice - num;
        var Ids = "";
        this.collectlist.forEach((item) => {
          Ids += item.id + ",";
        });
        this.collectlist = [];
        localStorage.setItem("cartSelectedList", []);
        this.$router.push({
          path: "/order/submit",
          query: {
            id: Ids.slice(0, Ids.length - 1),
          },
        });
      }
    },
  },
  computed: {
    ...mapState({
      cartRecommend: (state) => state.data.list.cartRecommend,
      data_cartproduct: (state) => state.data.cartproduct,
    }),
  },
  watch: {
    selectedNum(n) {
      setTimeout(() => {
        if (!this.data_cartproduct) return;
        if (n == this.data_cartproduct.length) {
          this.checked = true;
        } else {
          if (this.All) {
            this.checked = false;
          }
        }
      }, 0);
    },
    collectlist(n) {
      localStorage.setItem("cartSelectedList", JSON.stringify(n));
    },
  },
};
</script>

<style lang="less">
.cart {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  padding-top: 90px;
  .nav {
    width: 100%;
    height: 80px;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9;
    .safeguard {
      width: 100%;
      height: 40px;
      background-color: #f5f5f5;
      display: flex;
      justify-content: space-around;
      align-items: center;
      span {
        font-size: 12px;
        color: #8c8c8c;
        .van-icon {
          font-size: 0.28rem;
          vertical-align: -2px;
          margin-right: 3px;
        }
      }
    }
    .purchaseNum {
      width: 100%;
      height: 40px;
      background-color: #fff;
      line-height: 40px;
      padding-left: 10px;
      span {
        font-size: 14px;
      }
      .num {
        color: red;
        margin-left: 5px;
      }
      .btn {
        background-color: #fff;
        border: 1px solid #9e9e9e;
        outline: none;
        padding: 0 10px;
        font-size: 14px;
        line-height: normal;
        height: 25px;
        float: right;
        margin-top: 7.5px;
        margin-right: 10px;
        border-radius: 4px;
      }
    }
  }
  .productList {
    width: 100%;
    .empty {
      width: 100%;
      .van-empty {
        width: 100%;
        background-color: #fff;
        .van-empty__image {
          width: 207px;
          height: auto;
        }
      }
    }
    .goodslist {
      width: 100%;
      background-color: #f5f5f5;
      padding-bottom: 100px;
    }
  }
  .statistics {
    width: 100%;
    height: 50px;
    background-color: #fafafa;
    position: fixed;
    left: 0;
    bottom: 50px;
    padding: 0 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .selected {
      height: 100%;
      .van-checkbox {
        height: 100%;
      }
    }
    .purchase {
      span {
        color: red;
        margin-right: 10px;
      }
      .purchase_order {
        color: white;
        background-color: #e93323;
        border: none;
        outline: none;
        padding: 8px 20px;
        border-radius: 20px;
      }
      .collect,
      .del {
        background-color: #fff;
        border: 1px solid #c0c0c0;
        outline: none;
        border-radius: 20px;
        font-size: 14px;
        padding: 6px 20px;
        margin-left: 10px;
      }
      .collect {
        color: #ff3700;
        border-color: #ff3700;
      }
    }
  }
  .recommend {
    padding-bottom: 50px;
  }

  .slide-enter-active {
    animation: slide-in 0.6s ease-out;
  }
  .slide-leave-active {
    animation: slide-out 0.4s ease-out;
    /* 这里在离开的时候，需要让这个元素脱离标准流，不然后面的元素动不了 */
    position: absolute;
  }
  /* 想要让动画平滑一点，需要加v-move的类名，v-可以别name的值 */
  .slide-move {
    transition: all 0.8s;
  }
  @keyframes slide-in {
    from {
      transform: translateY(50px);
    }
    to {
      transform: translateY(0);
    }
  }
  @keyframes slide-out {
    from {
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }
}
</style>